package org.parosproxy.paros.core.proxy.custom;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.parosproxy.paros.network.HttpRequestHeader;

class SSLLinkBuilder {

	private static final Pattern filePattern = Pattern.compile("^(.*)/([^/]+)$");
	
	//
	private URLMonitor urlMonitor = URLMonitor.getInstance();

	private static Log log = LogFactory.getLog(SSLLinkBuilder.class);


	public SSLLinkBuilder(HttpRequestHeader heades) {
		// TODO Auto-generated constructor stub
	}

	public String stripFileFromPath(String path) {

		Matcher matcher = filePattern.matcher(path);
		if (matcher.matches()) {
			return matcher.group(1);
		}
		return null;
	}

	public void buildAbsoluteLink(String link,HttpRequestHeader headers,String client,String uri) {
		String absoluteLink = "";

		if ((link.indexOf("http") != 0) && (link.indexOf('/')) != 0) {
			absoluteLink = "http://" + headers.getHostName() + stripFileFromPath(uri) + '/' + link;

			log.debug("Found path-relative link in secure transmission: " + link);
			log.debug("New Absolute path-relative link: " + absoluteLink);
		} else if (link.indexOf("http") != 0) {
			absoluteLink = "http://" + headers.getHostName() + link;

			log.debug("Found relative link in secure transmission: " + link);
			log.debug("New Absolute link: " + absoluteLink);
		}
		if (!absoluteLink.equals("")) {
			absoluteLink = absoluteLink.replace("&amp;", "&");
			urlMonitor.addSecureLink(client, absoluteLink);
		}

	}
	
}
